package com.twotiger.and.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import app.twotiger.p2p.R;
import app.twotiger.p2p.R.color;

import com.lidroid.xutils.BitmapUtils;
import com.twotiger.and.Constants;
import com.twotiger.and.TwoTigerApp;
import com.twotiger.and.activity.HomeActivity;
import com.twotiger.and.activity.project.ProjectDetailPage;
import com.twotiger.and.activity.project.Projectpage;
import com.twotiger.and.activity.user.LoginPage;
import com.twotiger.and.bean.ProjectDetail;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.ListUtils;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;

/**
 * Created by victor on 2014/11/7 0007.
 */
public class ProjectAdapter extends BaseAdapter {
    private HomeActivity mactivity;
    private ArrayList<ProjectDetail> mList;
    private Projectpage mFragment;
    private BitmapUtils bitmapUtil;

    public ProjectAdapter(HomeActivity _Activity, ArrayList<ProjectDetail> _List,
                          Projectpage fragment) {
        this.mactivity = _Activity;
        this.mList = _List;
        this.mFragment = fragment;
        bitmapUtil = new BitmapUtils(mactivity);
    }

    public List<Integer> getComingProjectIndexs(int s, int n) {
        List<Integer> r = new ArrayList<Integer>();
        if (s < 0 || s > mList.size())
            s = 0;
        if (n > mList.size() || n < 0)
            n = mList.size();
        for (int i = s; i < n; i++) {
            ProjectDetail p = mList.get(i);
            if (p.getStatus() == Constants.PRO_STATUS_WAITING) {
                r.add(i);
            }
        }
        return r;
    }

    public void addData(List<ProjectDetail> _projectItems) {
        if (!ListUtils.isEmpty(_projectItems)) {
            mList.addAll(_projectItems);
        }
        notifyDataSetChanged();
    }

    public void resetData(List<ProjectDetail> _List) {
        mList.clear();
        if (!ListUtils.isEmpty(_List)) {
            mList.addAll(_List);
        }
        notifyDataSetChanged();
    }

    public ArrayList<ProjectDetail> getDataList() {
        return mList;
    }

    @Override
    public int getCount() {
        if (!ListUtils.isEmpty(mList)) {
            return mList.size();
        } else {
            return 10;
        }
    }

    @Override
    public ProjectDetail getItem(int position) {
        if (!ListUtils.isEmpty(mList) && position < mList.size()) {
            return mList.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    /**
     * @param position
     * @param convertView
     * @param parent
     * @return
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = View.inflate(mactivity, R.layout.project_p2p_item, null);
        }
        TextView project_name_tv = ViewHolder.get(convertView, R.id.project_name_tv);
        TextView project_active = ViewHolder.get(convertView, R.id.project_active);
        TextView project_amount_tv = ViewHolder.get(convertView, R.id.project_amount_tv);
        TextView project_yield_tv = ViewHolder.get(convertView, R.id.project_yield_tv);
        TextView project_awardYield_tv = ViewHolder.get(convertView, R.id.project_awardYield_tv);
        TextView timer_pre = ViewHolder.get(convertView, R.id.timer_pre);
        TextView timer_val = ViewHolder.get(convertView, R.id.timer_val);
        RelativeLayout rl_timer_count = ViewHolder.get(convertView, R.id.rl_timer_count);

        TextView project_awardYield_percent_tv = ViewHolder.get(convertView,
            R.id.project_awardYield_percent_tv);

        TextView project_period_tv = ViewHolder.get(convertView, R.id.project_period_tv);

        TextView tv_mortgage_type = ViewHolder.get(convertView, R.id.tv_mortgage_type);
        Button btn_buy = ViewHolder.get(convertView, R.id.btn_buy);

        final ProjectDetail projectItem = getItem(position);
        if (projectItem != null) {
            project_name_tv.setText(projectItem.getName() + "");
            tv_mortgage_type.setText(projectItem.getPledgeType());

            project_amount_tv.setText(ArithUtils.coverMoneyComma(projectItem.getRemainAmount()));
            project_yield_tv.setText(ArithUtils.formatProject(projectItem.getYield(), "#.#") + "");

            if (projectItem.getAwardYield() > 0) {
                project_awardYield_tv.setText(" +"
                                              + ArithUtils.formatProject(
                                                  projectItem.getAwardYield(), "#.##") + "");
                project_awardYield_percent_tv.setVisibility(View.VISIBLE);
                project_awardYield_tv.setVisibility(View.VISIBLE);
            } else {
                project_awardYield_percent_tv.setVisibility(View.GONE);
                project_awardYield_tv.setVisibility(View.GONE);
            }
            if (projectItem.getActivityMark() == 0) {
                project_active.setVisibility(View.GONE);
            } else {
                project_active.setVisibility(View.VISIBLE);
                project_active.setText(projectItem.getActivityName());
            }
            project_period_tv.setText(projectItem.getPeriod() + "");

            switch (projectItem.getStatus()) {
            case Constants.PRO_STATUS_WAITING: // 未开始（初审通过/待上架）
                btn_buy.setText("立即抢购");
                btn_buy.setEnabled(false);

                rl_timer_count.setVisibility(View.VISIBLE);
                timer_pre.setVisibility(View.VISIBLE);
                timer_val.setVisibility(View.VISIBLE);
                timer_val.setText(projectItem.getTime2Start());
                project_amount_tv.setTextColor(mactivity.getResources().getColor(color.gray_2));
                break;
            case Constants.PRO_STATUS_TRADING: // 募集中（已上架/融资中）
                btn_buy.setText("立即抢购");
                btn_buy.setEnabled(true);

                rl_timer_count.setVisibility(View.GONE);
                timer_pre.setVisibility(View.GONE);
                timer_val.setVisibility(View.GONE);

                project_amount_tv.setTextColor(mactivity.getResources().getColor(color.gray_2));
                break;
            case Constants.PRO_STATUS_FULFILL: // 募集完成（ 已满标/待复审）
            case Constants.PRO_STATUS_CHECK_WAIT: // 募集完成（复审通过/数据处理中）
                btn_buy.setText(projectItem.getStatusName() + "");
                btn_buy.setEnabled(false);

                rl_timer_count.setVisibility(View.GONE);
                timer_pre.setVisibility(View.GONE);
                timer_val.setVisibility(View.GONE);
                project_amount_tv.setTextColor(mactivity.getResources().getColor(color.gray_1));
                break;
            case Constants.PRO_STATUS_CHECKED: // 还款中（复审通过/还款中） 
            case Constants.PRO_STATUS_REPAYING: // 还款中（还款中/数据处理中）；
            case Constants.PRO_STATUS_REPAYMENT_EARLY: // 还款中（提前还款）
                btn_buy.setText(projectItem.getStatusName() + "");
                btn_buy.setEnabled(false);

                rl_timer_count.setVisibility(View.GONE);
                timer_pre.setVisibility(View.GONE);
                timer_val.setVisibility(View.GONE);
                project_amount_tv.setTextColor(mactivity.getResources().getColor(color.gray_1));
                break;
            case Constants.PRO_STATUS_REPAYMENT: //已还款（正常还款）
            case Constants.PRO_STATUS_REPAYMENT_LATE: // 已还款（逾期还款）
                btn_buy.setText(projectItem.getStatusName() + "");
                btn_buy.setEnabled(false);

                rl_timer_count.setVisibility(View.GONE);
                timer_pre.setVisibility(View.GONE);
                timer_val.setVisibility(View.GONE);
                project_amount_tv.setTextColor(mactivity.getResources().getColor(color.gray_1));
                break;
            case Constants.PRO_STATUS_LATE: // 逾期（逾期）
                btn_buy.setText(projectItem.getStatusName() + "");
                btn_buy.setEnabled(false);

                rl_timer_count.setVisibility(View.GONE);
                timer_pre.setVisibility(View.GONE);
                timer_val.setVisibility(View.GONE);
                project_amount_tv.setTextColor(mactivity.getResources().getColor(color.gray_1));
                break;
            }
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mactivity, ProjectDetailPage.class).putExtra(
                        "PROJECT_ID", projectItem.getProjectId()).putExtra("MODE",
                        projectItem.getMode());
                    mactivity.startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out,
                        false);
                }
            });
            btn_buy.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (projectItem.getStatus() != Constants.PRO_STATUS_TRADING) {
                        return;
                    }
                    if (!isLogin()) {
                        Intent intent = new Intent(mactivity, LoginPage.class).putExtra("FROM",
                            R.id.to_inverst);
                        mactivity.startNewActivity(intent, R.anim.slide_in_from_bottom,
                            R.anim.silent_anim, false);
                        return;
                    }
                    if (!hasOpenThirdAct()) {
                        PromptManager.showConfirmAlertCommon(mactivity, 0, "",
                            "您还未开通汇付天下托管账号，继续开通", "取消", "继续", true, new ReChargeClickListener() {

                                @Override
                                public void onClickConfirm() {

                                }

                                @Override
                                public void onClickCancel() {
                                    // 确认，则继续
                                    mFragment.openpayment();
                                }
                            });
                        return;
                    }
                    if (Constants.PRO_TYPE_NEWER.equals(projectItem.getMode())) { //新手项目非新手不可点
                        if (!mFragment.isNewMan()) {
                            mactivity.showToast("新手项目仅限第一次投资");
                            return;
                        }
                    }
                    mFragment.getProjectDetail(projectItem.getProjectId(), projectItem.getMode());
                }

            });
        }
        return convertView;
    }

    protected boolean hasOpenThirdAct() {
        return TwoTigerApp.getInstance().getUser().hasOpenThirdAct;
    }

    protected boolean isLogin() {
        if (!TextUtils.isEmpty(TwoTigerApp.getInstance().getUser().token)) {
            return true;
        }
        return false;
    }
}
